package com.company;

import org.junit.Test;

import java.util.ArrayList;
import java.util.List;

public class ThreadTest {

    @Test
    public void test01() throws InterruptedException {
        Thread t1 = new Thread(() -> {
            for (int i = 1000; i < 2000; i++) {
                System.out.println(Thread.currentThread().getName() + "---" + i);
            }
        });
        t1.start();

        new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                try {
                    t1.join(200);
                    System.out.println(Thread.currentThread().getName() + "---" + i);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        ).start();

        Thread.sleep(20000);

    }

    @Test
    public void test03() {

    }

    public static class TestProdCons {
        //定义一个存放热狗的集合，里面存放的是整数，代表热狗编号
        private static final List<Integer> hotDogs = new ArrayList<Integer>();

        public static void main(String[] args) {
            for (int i = 1; i <= 1; i++) {
                new Producer(i).start();
            }
            for (int i = 1; i <= 1; i++) {
                new Consumer(i).start();
            }
            try {
                Thread.sleep(20000000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        //生产者线程，以热狗集合作为对象锁，所有对热狗集合的操作互斥
        private static class Producer extends Thread {
            int i = 1;
            int pid = -1;

            public Producer(int id) {
                this.pid = id;
            }

            public synchronized void run() {
                while (true) {
                    if (hotDogs.size() < 10) {
                        //热狗编号，300002代表编号为3的生产者生产的第2个热狗
                        hotDogs.add(pid * 10000 + i);
                        System.out.println("生产者" + pid + "生产热狗，编号为：" + pid * 10000 + i);
                        i++;
                    } else {
                        System.out.println("热狗数已到10个，等待消费！");
                    }
                }
            }
        }

        //消费者线程，以热狗集合作为对象锁，所有对热狗集合的操作互斥
        private static class Consumer extends Thread {
            int cid = -1;

            public Consumer(int id) {
                this.cid = id;
            }

            public synchronized void run() {
                while (true) {
                    if (hotDogs.size() > 0) {
                        System.out.println("消费者" + this.cid + "正在消费一个热狗，其编号为：" + hotDogs.remove(0));
                    } else {
                        System.out.println("已没有热狗，等待生产！");
                    }
                }
            }
        }
    }

}
